package cn.tedu.zx.album.adapter.impl;


import cn.tedu.zx.album.adapter.mapper.AlbumMapper;
import cn.tedu.zx.album.adapter.mapper.PictureMapper;
import cn.tedu.zx.album.service.PictureService;
import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.common.restful.JsonPage;
import cn.tedu.zx.common.restful.ResponseCode;
import cn.tedu.zx.pojo.court.dto.PictureAddNewDto;
import cn.tedu.zx.pojo.court.dto.PictureUpdateDto;
import cn.tedu.zx.pojo.court.entity.Picture;
import cn.tedu.zx.pojo.court.vo.PictureDetailsVo;
import cn.tedu.zx.pojo.court.vo.PictureListVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class PictureServiceImpl implements PictureService {
    private String message = null;

    @Value("${zx.resource.base-dir}")
    private String baseDir;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private AlbumMapper albumMapper;

    Picture picture = new Picture();

    @Override
    public void addNew(PictureAddNewDto pictureAddNewDto) {
        log.debug("往相册添加文件");

        //检查数据冲突情况
        checkConflict(pictureAddNewDto.getUrl(), 0L);


        BeanUtils.copyProperties(pictureAddNewDto, picture);
        picture.setCreated(LocalDateTime.now());
        picture.setUpdated(LocalDateTime.now());
        log.trace("往数据库添加子项：{}", picture);
        int insert = pictureMapper.insert(picture);

        //检查操作是否全部成功
        operateFailed(insert);

        log.trace("{}添加完成", picture);
    }

    @Override
    public void deleteById(Long id) {
        log.debug("{}", id);

        //检查数据是否存在
        checkEmpty(id);

        //搜素本地图片文件并进行修改
        deleteImg(id);

        int delete = pictureMapper.deleteById(id);

        //检查操作是否全部成功
        operateFailed(delete);
    }

    @Override
    public void updateById(PictureUpdateDto pictureUpdateDto) {
        log.debug("{}", pictureUpdateDto);

        //检查数据是否存在
        checkEmpty(pictureUpdateDto.getId());

        //检查数据冲突情况
        checkConflict(pictureUpdateDto.getUrl(), pictureUpdateDto.getId());

        //搜素本地图片文件并进行修改
        deleteImg(pictureUpdateDto.getId());

        BeanUtils.copyProperties(pictureUpdateDto, picture);
        picture.setUpdated(LocalDateTime.now());
        log.trace("往数据库修改子项：{}", picture);
        int updateById = pictureMapper.updateById(picture);

        //检查操作是否全部成功
        operateFailed(updateById);
        log.trace("{}修改完成", picture);
    }


    @Override
    public PictureDetailsVo selectDetailsById(Long id) {
        log.debug("传入的id：{}", id);
        PictureDetailsVo pictureDetailsVo = pictureMapper.selectDetailsById(id);
        log.debug("查到的数据：{}", pictureDetailsVo);

        //检查数据是否存在
        if (pictureDetailsVo == null) {
            message = "查询失败，根据【id=" + id + "】查询的相册详情不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        return pictureDetailsVo;
    }

    @Override
    public JsonPage list(Integer pageNum, Integer albumId) {
        Integer pageSize = 5;
        return list(pageNum, pageSize, albumId);
    }

    @Override
    public JsonPage<PictureListVo> list(Integer pageNum, Integer pageSize, Integer albumId) {
        PageHelper.startPage(pageNum, pageSize);
        List<PictureListVo> list = pictureMapper.list(albumId);
        PageInfo pageInfo = new PageInfo(list);
        return JsonPage.restPage(pageInfo);
    }

    // 设置为封面
    @Override
    public void setCover(Long id) {
        //检查数据是否存在
        checkEmpty(id);

        PictureDetailsVo pictureVO = pictureMapper.selectDetailsById(id);

        //检查图片是否已经是封面
        if (pictureVO.getIsCover()==1){
            message= "该图片已经是封面不需要重复设置";
            throw  new ServiceException(ResponseCode.CONFLICT,message);
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",pictureVO.getAlbumId());
        Integer rows = albumMapper.selectCount(queryWrapper);
        //检查图片所在相册是否存在
        if (rows < 0) {
            message = "图片所在相册不存在";
            throw  new ServiceException(ResponseCode.CONFLICT,message);
        }

        //将该相册下所有图片都设为非封面
        picture.setIsCover(0);
        rows = pictureMapper.update(picture, queryWrapper);
        operateFailed(rows);

        //将目标图片设为封面
        picture.setId(id).setIsCover(1);
        rows = pictureMapper.updateById(picture);
        operateFailed(rows);
    }


    @Override
    public List<String> slideshowList() {
        List<String> list = pictureMapper.selectSlideshowList();
        return list;
    }

    @Override
    public void slideshowChange(Long id, Integer slideshow) {
        Picture picture1 =new Picture();
        picture1.setId(id);
        picture1.setSlideshow(slideshow);
        pictureMapper.updateById(picture1);
    }

    @Override
    public void updateDescription(Long id, String description) {
        pictureMapper.updateDescription(id,description);
    }


    /**
     * 通过id检查数据是否存在
     * @param id
     */
    private void checkEmpty(Long id) {
        QueryWrapper<Picture> albumWrapper = new QueryWrapper();
        albumWrapper.eq("id", id);
        int countById = pictureMapper.selectCount(albumWrapper);
        if (countById == 0) {
            message = "操作失败，数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
    }


    /**
     * 文件操作是否与预测一致
     * @param operatedRows
     */
    private void operateFailed(Integer operatedRows) {
        if (operatedRows < 1) {
            String message = "服务器忙,请稍后再试";
            throw new ServiceException(ResponseCode.INTERNAL_SERVER_ERROR, message);
        }
    }


    /**
     * 通过名称字段及id检查内容是否冲突
     * @param url
     * @param id
     */
    private void checkConflict(String url, Long id) {
        QueryWrapper<Picture> categoryWrapper = new QueryWrapper();
        categoryWrapper.eq("url", url).ne("id", id);
        int countByName = pictureMapper.selectCount(categoryWrapper);
        log.debug("查询数据{}", countByName);
        if (countByName > 0) {
            message = "操作失败，图片地址已占用";
            log.warn(message);
            throw new ServiceException(ResponseCode.CONFLICT, message);
        }
    }


    /**
     * 通过id查询相关路径并删除本地图片文件
     * @param id
     */
    private void deleteImg(Long id){

        String oldUrl = pictureMapper.selectDetailsById(id).getUrl();

        //url使用端口拼接
        String substring = oldUrl.substring(oldUrl.indexOf("/picture"));

        log.trace("获取路径：{}",substring);
        String url = baseDir + substring;
        //url不加端口拼接

//        String url = baseDir+"/"+oldUrl;

        File file = new File(url);

        if (file.exists()) {
            file.delete();
        }
    }


}
